package com.jee.ssm.modules.rescue.app;

import com.alibaba.fastjson.JSON;
import com.jee.ssm.common.socket.rescue.RescueUtil;
import com.jee.ssm.common.utils.TokenUtils;
import com.jee.ssm.common.utils.UUIDFactory;
import com.jee.ssm.model.Account;
import com.jee.ssm.model.Rescue;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.modules.rescue.services.RescueService;
import com.jee.ssm.modules.ssm.services.AccountService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

/**
* 救援管理 客户端 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/app/rescue")
public class AppRescueController {


	/**
	 * 提交紧急求助
	 */
	@RequestMapping(value = "/saveRescue", method = RequestMethod.GET)
	@ResponseBody
	public Tip saveRescue(long timestamp, String token, String phone, String lat, String lng) {
		Tip tip = TokenUtils.verifyToken(timestamp, token);
//        if(tip.getSuccess()) {
        	Rescue rescue = new Rescue(UUIDFactory.getStringId(), new Date(), phone, lat == null || "".equals(lat) ? null : Double.valueOf(lat), lng == null || "".equals(lng) ? null : Double.valueOf(lng), 0, 0 );
    		try {
    			rescueService.insert(rescue);
    			int num = 0;
    			List<Account> list = accountService.findRescueReceipt();
    			for(Account a : list) {
    				WebSocketSession s = RescueUtil.get(a.getId());
    				if(s != null) {
    					s.sendMessage(new TextMessage(JSON.toJSONString(rescue)));
    					num ++;
    				}
    			}
    			if(num > 0) {
    				tip = new Tip("当前已有" + num + "位客服人员接收到您的紧急救援，稍后会有工作人员与您联系，请耐心等待");
    			} else {
    				tip = new Tip(2, "客服人员均不在线");
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    			tip = new Tip(1, "请求失败");
    		}
//        }
		
		return tip;
	}





    //---------------------------- property -------------------------------

    @Resource
    private RescueService rescueService;
    
    @Resource
    private AccountService accountService;

}
